'use strict';

const axios = require('axios')
const urlJoin = require('url-join')
const semver = require('semver')

/**
 * 获取当前仓库的基本信息 https://registry.npmjs.org/@tangmen-cli-dev/core
 * @param {*} npmName
 * @param {*} registry
 */
function getNpmInfo(npmName, registry) {
    if (!npmName) {
        return null
    }
    const registryUrl = registry || getDefaultRegistry(false)
    const npmInfoUrl = urlJoin(registryUrl, npmName)
    return axios.get(npmInfoUrl).then((response) => {
        if (response.status === 200) {
            return response.data
        }
        return null
    }).catch((error) => {
        return Promise.reject(error)
    })
}

// 获取默认的registryUrl 默认是淘宝源
function getDefaultRegistry(isOrigin = false) {
    return isOrigin ? 'https://registry.npmjs.org' : 'https://registry.npm.taobao.org'
}

// 获取所有版本号
async function getNpmVersions(npmName, registry) {
    const data = await getNpmInfo(npmName, registry)
    if (data) {
        return Object.keys(data.versions)
    } else {
        return []
    }
}

// 获取最新版本号
async function getNpmLastVersion(npmName, registry) {
    let versions = await getNpmVersions(npmName, registry)
    if (versions) {
        return versions.sort((a, b) => semver.gt(b, a))[0]
    }
    return null
}

// 过滤超过baseVersion的版本 然后排序一下
function getSemverVersions(baseVersion, versions) {
    return versions.filter(version => semver.satisfies(version, `>${baseVersion}`)).sort((a, b) => semver.gt(b, a))
}

// 拿到比当前版本高的所有版本
async function getNpmSemverVersion(baseVersion, npmName, registry) {
    // 拿到所有的版本号
    const versions = await getNpmVersions(npmName, registry)
    // 拿到当前版本以后的版本
    const newVersions = getSemverVersions(baseVersion, versions)
    if (newVersions && newVersions.length > 0) {
        return newVersions[0]
    }
    return null
}

module.exports = {getNpmInfo, getNpmLastVersion, getNpmSemverVersion, getNpmVersions, getDefaultRegistry};
